const fs = require("fs");
const os = require("os");
const path = require("path");

const xlsx = require("./node_modules/node-xlsx/dist/index.cjs").default;
window.$xlsx = xlsx;
const { clipboard } = require("electron");
console.log(" require('electron')", require("electron"));
// 获取剪贴板内容
const clip = clipboard;
window.$clip = clip;

const json = require("./config.json");
const _json = JSON.parse(JSON.stringify(json));
const axios = require("./node_modules/axios/dist/node/axios.cjs").default;
window.axios = axios;
// 获取配置文件
window.$config = json;
window.$initConfig = () => {
  window.$config = JSON.parse(JSON.stringify(_json));
};
function checkFileExists(path) {
  try {
    return fs.existsSync(path);
  } catch (error) {
    return false;
  }
}

// 创建临时文件
function createTempFile(content) {
  const tempDir = os.tmpdir();
  const tempFilePath = path.join(tempDir, `tempScript_${Date.now()}.js`);
  // 2. 创建并写入内容
  fs.writeFileSync(tempFilePath, content, "utf8");
  return tempFilePath;
}
// 清除文件
function deleteFile(path) {
  fs.unlink(path, (err) => {
    if (err) {
      console.error(`file delete error`, err);
    }
    console.log(`Temporary file deleted: ${path}`);
  });
}

// 文件路径不存在创建文件夹和文件

async function createFileIfNotExist(path) {
  if (!checkFileExists(path)) {
    const dirPath = path.split("/").slice(0, -1).join("/");
    await createDirIfNotExist(dirPath);
    // await writeFile(path, JSON.stringify({}));
  }
}

// 创建文件夹

async function createDirIfNotExist(path) {
  if (!checkFileExists(path)) {
    await new Promise((resolve, reject) => {
      fs.mkdir(path, { recursive: true }, (err) => {
        if (err) {
          return reject(err);
        }
        resolve();
        console.log("Folder created successfully!");
      });
    });
  }
}
// 创建文件
async function writeFile(path, contents) {
  console.log("checkFileExists(path);", checkFileExists(path));
  if (!checkFileExists(path)) {
    await createFileIfNotExist(path);
  }
  new Promise((resolve, reject) => {
    fs.writeFile(path, contents, (err) => {
      if (err) {
        return reject(err);
      }
      resolve();
      console.log("Configuration file created successfully!");
    });
  });
}

function readFile(path) {
  try {
    const contents = fs.readFileSync(path, "utf8");
    return contents;
  } catch (error) {
    return null;
  }
}
window.$writeFile = writeFile;
window.$checkFileExists = checkFileExists;
window.$createFileIfNotExist = createFileIfNotExist;
window.$readFile = readFile;
window.$createTempFile = createTempFile;
window.$deleteFile = deleteFile;
